#include <stdlib.h>


#include "global.h"
#include "NodeTable.h"
#include "Pop.h"
#include "Xover.h"


CXover::CXover(void)
{
}

CXover::~CXover(void)
{
}

bool CXover::NpointCX(Chro* ch0,Chro* res, int nCh)
{
	float cut[MAXCLASS]={0,};
	int i,j;
	int cutlen = rand()%nCh;

	if(cutlen == 0)cutlen = 1;
	
	for(i =0; i< cutlen;i++)
	{
		cut[i] = (rand()/((float)RAND_MAX))*nCh;
	}
	fsort(cut,cutlen);
	cut[0] = (float)(int)(cut[0]);
	if(cut[0] == 0.0)
		cut[0] = 1;

	for(i =1; i< cutlen;i++)
	{
		cut[i] = (float)(int)(cut[i]);
		if(cut[i] <= cut[i-1])
		{
			cut[i] = cut[i-1] + 1;
		}
	}


	int toggle=0;j=0;

	
	for(i = 0; i< nCh;i++)
	{
		//res->gene[i] = ch0[toggle].gene[i];
		res->UpdateNode(i,ch0[toggle].GetGene(i));
		if(j<cutlen &&  i>=cut[j])
		{
			toggle = (toggle+1)%2;j++;
		}
	}
	return true;
}

bool CXover::point4CX(Chro* ch0,Chro* res, int nCh)
{
	float cut[4]={0,};
	int i,j;
	int cutlen = 4;

	if(cutlen == 0)cutlen = 1;
	
	for(i =0; i< cutlen;i++)
	{
		cut[i] = (rand()/((float)RAND_MAX))*nCh;
	}
	fsort(cut,cutlen);
	cut[0] = (float)(int)(cut[0]);
	if(cut[0] == 0.0)
		cut[0] = 1;

	for(i =1; i< cutlen;i++)
	{
		cut[i] = (float)(int)(cut[i]);
		if(cut[i] <= cut[i-1])
		{
			cut[i] = cut[i-1] + 1;
		}
	}


	int toggle=0;j=0;
	for(i = 0; i< nCh;i++)
	{
		//res->gene[i] = ch0[toggle].gene[i];
		res->UpdateNode(i,ch0[toggle].GetGene(i));
		if(j<cutlen &&  i>=cut[j])
		{
			toggle = (toggle+1)%2;j++;
		}
	}
	return true;
}
bool CXover::point2CX(Chro* ch0,Chro* res, int nCh)
{
	float cut[4]={0,};
	int i,j;
	int cutlen = 2;

	if(cutlen == 0)cutlen = 1;
	
	for(i =0; i< cutlen;i++)
	{
		cut[i] = (rand()/((float)RAND_MAX))*nCh;
	}
	fsort(cut,cutlen);
	cut[0] = (float)(int)(cut[0]);
	if(cut[0] == 0.0)
		cut[0] = 1;

	for(i =1; i< cutlen;i++)
	{
		cut[i] = (float)(int)(cut[i]);
		if(cut[i] <= cut[i-1])
		{
			cut[i] = cut[i-1] + 1;
		}
	}


	int toggle=0;j=0;
	for(i = 0; i< nCh;i++)
	{
		//res->gene[i] = ch0[toggle].gene[i];
		res->UpdateNode(i,ch0[toggle].GetGene(i));
		if(j<cutlen &&  i>=cut[j])
		{
			toggle = (toggle+1)%2;j++;
		}
	}
	return true;
}